package test

import (
	"context"
	"fmt"
	clientv3 "go.etcd.io/etcd/client/v3"
	"time"
)

func main2() {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"192.168.64.128:2379"}, //如果是集群，就在后面加所有的节点[]string{"localhost:2379", "localhost:22379", "localhost:32379"},
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		// handle error!
		fmt.Printf("connect to etcd failed, err:%v\n", err)
		return
	}
	defer cli.Close()

	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	_, err = cli.Put(ctx, "address", "成都市高新区")

	if err != nil {
		fmt.Printf("put to etcd failed, err:%v\n", err)
		return
	}
	fmt.Println("put to etcd success")

	fmt.Println("put to etcd success,开始读取数据")

	resp, err := cli.Get(ctx, "address")
	if err != nil {
		fmt.Printf("读取失败get from etcd failed, err:%v\n", err)
		return
	}
	//fmt.Printf("读取成功 resp:%v\n", resp)
	for _, v := range resp.Kvs {
		fmt.Printf("读取成功 key:%s, value:%s\n", string(v.Key), string(v.Value))
	}
	defer cancel() // 这里如果在同一个地方操作读写,需要加defer
}

// 想要拆分etcd的初始化和使用代码失败,放在一起可以运行,拆开以后会报错需要处理
